package org.railage.client.gui.tabs;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;
import org.railage.client.Client;
import org.railage.client.gui.main.GUI;
import org.railage.common.dto.TicketOfUserDTO;

public class BoughtTicketsTab extends AbstractTab {

	private static final long serialVersionUID = 7869887107404755908L;

	private static final Logger log = Logger.getLogger(BoughtTicketsTab.class);

	private SimpleDateFormat dateTimeFormatter = new SimpleDateFormat(
			GUI.DATE_FORMAT + " " + GUI.TIME_FORMAT);

	private JTable ticketTable;

	private String[] columnNames = new String[] { "Trip ID", "Route",
			"Departure time", "Departure station", "Arrival time",
			"Arrival station" };

	public BoughtTicketsTab() {
		setLayout(null);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 0, 720, 390);
		add(scrollPane);

		ticketTable = new JTable();
		scrollPane.setViewportView(ticketTable);
	}

	public void init() {
		Object[][] data = new Object[][] {};
		TicketOfUserDTO[] tickets = null;
		int userID = Client.getInstance().getCurrentUser().getId();
		try {
			tickets = (TicketOfUserDTO[]) Client.getInstance().callMethod(
					"getAllTicketsOfUser", userID);
			data = new Object[tickets.length][];
			int i = 0;
			for (TicketOfUserDTO ticket : tickets) {
				data[i] = new Object[] { ticket.getTripID(),
						ticket.getRouteName(),
						dateTimeFormatter.format(ticket.getDepartureTime()),
						ticket.getDepartureStation(),
						dateTimeFormatter.format(ticket.getArrivalTime()),
						ticket.getArrivalStation() };
				i++;
			}
		} catch (IOException e) {
			log.error(GUI.DISCON_UNEXP_LOG_MSG, e);
			JOptionPane.showMessageDialog(this, GUI.DISCON_UNEXP_GUI_MSG);
		}
		ticketTable.setModel(new DefaultTableModel(data, columnNames) {
			private static final long serialVersionUID = -1664588208999596181L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		});
	}
}
